package com.kuang.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Administrator
 * @date 2021/5/28 16:05
 * Description:
 */
public class SpinLockDemo {
    // int 初始值 0
    // Thread 初始值 null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void myLock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"===> myLock");
        //自旋锁
        while (!atomicReference.compareAndSet(null, thread)) {
            System.out.println(Thread.currentThread().getName()+" is waiting");
        }
    }

    //解锁
    public void myUnlock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"===> myUnlock");
        atomicReference.compareAndSet(thread, null);
    }
}
